package com.vehiclemanagement.controller;

import com.vehiclemanagement.common.result.Result;
import com.vehiclemanagement.dto.StatisticsDTO;
import com.vehiclemanagement.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图表数据控制器
 * 用于处理前端图表展示所需的数据
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Autowired
    private ReportService reportService;

    /**
     * 获取车辆使用趋势图数据
     */
    @GetMapping("/vehicle/usage/trend")
    public Result<Map<String, Object>> getVehicleUsageTrend(
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Integer year) {
        
        log.info("获取车辆使用趋势图数据: vehicleId={}, year={}", vehicleId, year);
        
        // 设置查询时间范围
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        
        if (year != null) {
            startTime = LocalDateTime.of(year, 1, 1, 0, 0);
            endTime = LocalDateTime.of(year, 12, 31, 23, 59, 59);
        } else {
            // 默认查询当年数据
            int currentYear = LocalDateTime.now().getYear();
            startTime = LocalDateTime.of(currentYear, 1, 1, 0, 0);
            endTime = LocalDateTime.of(currentYear, 12, 31, 23, 59, 59);
        }
        
        try {
            // 获取车辆使用统计数据
            List<Map<String, Object>> statistics = reportService.getVehicleUsageStatistics(vehicleId, startTime, endTime);
            
            // 转换为图表数据
            Map<String, Object> result = new HashMap<>();
            List<String> months = new ArrayList<>();
            List<Integer> useCounts = new ArrayList<>();
            List<Double> mileages = new ArrayList<>();
            List<Integer> hours = new ArrayList<>();
            
            for (Map<String, Object> stat : statistics) {
                months.add(stat.get("month").toString());
                useCounts.add(Integer.parseInt(stat.get("use_count").toString()));
                mileages.add(Double.parseDouble(stat.get("total_mileage").toString()));
                hours.add(Integer.parseInt(stat.get("total_hours").toString()));
            }
            
            result.put("months", months);
            result.put("useCounts", useCounts);
            result.put("mileages", mileages);
            result.put("hours", hours);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取车辆使用趋势图数据失败", e);
            return Result.error("获取车辆使用趋势图数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取费用分布饼图数据
     */
    @GetMapping("/cost/distribution/pie")
    public Result<Map<String, Object>> getCostDistributionPie(
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) Integer month) {
        
        log.info("获取费用分布饼图数据: year={}, month={}", year, month);
        
        try {
            // 获取费用分布统计数据
            List<Map<String, Object>> distribution = reportService.getCostDistribution(year, month);
            
            // 转换为饼图数据
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> pieData = new ArrayList<>();
            
            for (Map<String, Object> cost : distribution) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", cost.get("cost_type"));
                item.put("value", cost.get("cost_value"));
                pieData.add(item);
            }
            
            result.put("pieData", pieData);
            
            // 计算总成本
            double totalCost = 0.0;
            for (Map<String, Object> cost : distribution) {
                totalCost += Double.parseDouble(cost.get("cost_value").toString());
            }
            result.put("totalCost", totalCost);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取费用分布饼图数据失败", e);
            return Result.error("获取费用分布饼图数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取ETC费用趋势图数据
     */
    @GetMapping("/etc/trend")
    public Result<Map<String, Object>> getETCTrend(
            @RequestParam(required = false) Integer year) {
        
        // 设置查询年份
        if (year == null) {
            year = LocalDateTime.now().getYear();
        }
        
        log.info("获取ETC费用趋势图数据: year={}", year);
        
        try {
            // 获取ETC通行费用统计数据
            List<Map<String, Object>> passageStats = reportService.getETCStatistics(year, null, 1);
            // 获取ETC停车费用统计数据
            List<Map<String, Object>> parkingStats = reportService.getETCStatistics(year, null, 2);
            
            // 转换为图表数据
            Map<String, Object> result = new HashMap<>();
            List<String> months = new ArrayList<>();
            List<Double> passageFees = new ArrayList<>();
            List<Double> parkingFees = new ArrayList<>();
            
            // 初始化12个月的数据
            for (int i = 1; i <= 12; i++) {
                String monthStr = String.format("%d-%02d", year, i);
                months.add(monthStr);
                passageFees.add(0.0);
                parkingFees.add(0.0);
            }
            
            // 填充通行费用数据
            for (Map<String, Object> stat : passageStats) {
                String month = stat.get("month").toString();
                Double fee = Double.parseDouble(stat.get("total_fee").toString());
                int index = months.indexOf(month);
                if (index >= 0) {
                    passageFees.set(index, fee);
                }
            }
            
            // 填充停车费用数据
            for (Map<String, Object> stat : parkingStats) {
                String month = stat.get("month").toString();
                Double fee = Double.parseDouble(stat.get("total_fee").toString());
                int index = months.indexOf(month);
                if (index >= 0) {
                    parkingFees.set(index, fee);
                }
            }
            
            result.put("months", months);
            result.put("passageFees", passageFees);
            result.put("parkingFees", parkingFees);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取ETC费用趋势图数据失败", e);
            return Result.error("获取ETC费用趋势图数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取违章事故统计图数据
     */
    @GetMapping("/violation/accident/stats")
    public Result<Map<String, Object>> getViolationAccidentStats(
            @RequestParam(required = false) Integer year) {
        
        // 设置查询年份
        if (year == null) {
            year = LocalDateTime.now().getYear();
        }
        
        log.info("获取违章事故统计图数据: year={}", year);
        
        try {
            // 获取违章统计数据
            List<Map<String, Object>> violationStats = reportService.getViolationStatistics(year, null);
            // 获取事故统计数据
            List<Map<String, Object>> accidentStats = reportService.getAccidentStatistics(year, null);
            
            // 转换为图表数据
            Map<String, Object> result = new HashMap<>();
            
            // 违章类型和数量
            List<String> violationTypes = violationStats.stream()
                    .map(stat -> stat.get("type").toString())
                    .collect(Collectors.toList());
            List<Integer> violationCounts = violationStats.stream()
                    .map(stat -> Integer.parseInt(stat.get("count").toString()))
                    .collect(Collectors.toList());
            
            // 事故等级和数量
            List<String> accidentLevels = accidentStats.stream()
                    .map(stat -> "级别" + stat.get("level").toString())
                    .collect(Collectors.toList());
            List<Integer> accidentCounts = accidentStats.stream()
                    .map(stat -> Integer.parseInt(stat.get("count").toString()))
                    .collect(Collectors.toList());
            
            result.put("violationTypes", violationTypes);
            result.put("violationCounts", violationCounts);
            result.put("accidentLevels", accidentLevels);
            result.put("accidentCounts", accidentCounts);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取违章事故统计图数据失败", e);
            return Result.error("获取违章事故统计图数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取运营成本分析仪表盘数据
     */
    @GetMapping("/operation/cost/dashboard")
    public Result<Map<String, Object>> getOperationCostDashboard(
            @RequestParam(required = false) Integer year) {
        
        // 设置查询年份
        if (year == null) {
            year = LocalDateTime.now().getYear();
        }
        
        log.info("获取运营成本分析仪表盘数据: year={}", year);
        
        try {
            // 获取总体运营成本分析
            Map<String, Object> costAnalysis = reportService.getOperationCostAnalysis(year);
            
            // 转换为仪表盘数据
            Map<String, Object> result = new HashMap<>();
            Double totalCost = (Double) costAnalysis.get("totalCost");
            
            result.put("totalCost", totalCost);
            result.put("costDistribution", costAnalysis.get("costDistribution"));
            result.put("monthlyCosts", costAnalysis.get("monthlyCosts"));
            
            // 计算同比和环比
            // 这里需要查询上一年和上个月的数据，简化起见，暂时使用随机数据
            double lastYearCost = totalCost * 0.9;  // 模拟数据
            double lastMonthCost = totalCost / 12 * 0.95;  // 模拟数据
            
            double yearOverYearGrowth = (totalCost - lastYearCost) / lastYearCost * 100;
            double monthOverMonthGrowth = (totalCost / 12 - lastMonthCost) / lastMonthCost * 100;
            
            result.put("yearOverYearGrowth", yearOverYearGrowth);
            result.put("monthOverMonthGrowth", monthOverMonthGrowth);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取运营成本分析仪表盘数据失败", e);
            return Result.error("获取运营成本分析仪表盘数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取驾驶员工作统计图数据
     */
    @GetMapping("/driver/work/stats")
    public Result<Map<String, Object>> getDriverWorkStats(
            @RequestParam(required = false) Long driverId,
            @RequestParam(required = false) Integer year) {
        
        // 设置查询时间范围
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        
        if (year != null) {
            startTime = LocalDateTime.of(year, 1, 1, 0, 0);
            endTime = LocalDateTime.of(year, 12, 31, 23, 59, 59);
        } else {
            // 默认查询最近一年数据
            startTime = LocalDateTime.now().minusYears(1);
            endTime = LocalDateTime.now();
        }
        
        log.info("获取驾驶员工作统计图数据: driverId={}, year={}", driverId, year);
        
        try {
            // 获取驾驶员工作统计数据
            List<Map<String, Object>> statistics = reportService.getDriverWorkStatistics(driverId, startTime, endTime);
            
            // 转换为图表数据
            Map<String, Object> result = new HashMap<>();
            List<String> months = new ArrayList<>();
            List<Integer> driveCounts = new ArrayList<>();
            List<Double> mileages = new ArrayList<>();
            List<Integer> hours = new ArrayList<>();
            
            for (Map<String, Object> stat : statistics) {
                months.add(stat.get("month").toString());
                driveCounts.add(Integer.parseInt(stat.get("drive_count").toString()));
                mileages.add(Double.parseDouble(stat.get("total_mileage").toString()));
                hours.add(Integer.parseInt(stat.get("total_hours").toString()));
            }
            
            result.put("months", months);
            result.put("driveCounts", driveCounts);
            result.put("mileages", mileages);
            result.put("hours", hours);
            
            // 如果有指定驾驶员，获取综合分析数据
            if (driverId != null) {
                Map<String, Object> driverAnalysis = reportService.getDriverAnalysis(driverId);
                result.put("driverInfo", driverAnalysis.get("driverInfo"));
                result.put("violationCount", driverAnalysis.get("violationCount"));
                result.put("accidentCount", driverAnalysis.get("accidentCount"));
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取驾驶员工作统计图数据失败", e);
            return Result.error("获取驾驶员工作统计图数据失败: " + e.getMessage());
        }
    }
} 